package com.wangzhixuan.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import java.util.UUID;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.wangzhixuan.commons.result.PageInfo;
import com.wangzhixuan.commons.utils.ResponseUtil;
import com.wangzhixuan.commons.utils.StringUtils;
import com.wangzhixuan.model.Craftsman;
import com.wangzhixuan.model.Production;
import com.wangzhixuan.model.Productionimg;
import com.wangzhixuan.model.Producttag;
import com.wangzhixuan.model.TTag;
import com.wangzhixuan.service.ICraftsmanService;
import com.wangzhixuan.service.IProductionService;
import com.wangzhixuan.service.IProductionimgService;
import com.wangzhixuan.service.IProducttagService;
import com.wangzhixuan.service.ITTagService;

import net.sf.json.JSONObject;

import com.wangzhixuan.commons.base.BaseController;

/**
 * <p>
 * </p>
 *
 * @author Yvan
 * @since 2017-06-28
 */
@Controller
@RequestMapping("/miiiind")
public class MiiiindController extends BaseController {
    @Autowired private ICraftsmanService craftsmanService;
    @Autowired private IProductionService productionService;
    @Autowired private IProductionimgService productionimgService;
    @Autowired private ITTagService tTagService;
    @Autowired private IProducttagService producttagService;
    
    @InitBinder  
    public void initBinder(WebDataBinder binder) {  
    	SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
	    dateFormat1.setLenient(false);  
	    binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat1, true)); 
	    
	    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");  
	    dateFormat.setLenient(false);  
	    binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));   //true:允许输入空值，false:不能为空值
    }
    
    @GetMapping("/index")
    public String index(Model model,Craftsman craftsman, Integer page, Integer rows, String sort,String order) {
    	if(page==null)
    		page=1;
    	if(rows==null){
    		rows=15;
    	}
    	PageInfo pageInfo = new PageInfo(page, rows, sort, order);
        EntityWrapper<Craftsman> ew = new EntityWrapper<Craftsman>();
 	    if(StringUtils.isNotBlank(craftsman.getManBrand())){
 	        ew.like("man_brand", craftsman.getManBrand());
 	    }
 	    
 	    if(StringUtils.isNotBlank(craftsman.getManCompany())){
 	        ew.like("man_company", craftsman.getManCompany());
 	    }
 	    
 	    if(StringUtils.isNotBlank(craftsman.getManName())){
 	        ew.like("man_name", craftsman.getManName());
 	    }
 	    if(StringUtils.isNotBlank(craftsman.getManType())){
	        ew.eq("man_type", craftsman.getManType());
	    }
 	   
 	   	ew.orderBy("id", false);
        Page<Craftsman> pages = getPage(pageInfo);
        pages = craftsmanService.selectPage(pages, ew);
        //获取产品数量
        if(pages.getRecords()!=null && pages.getRecords().size()>0){
        	for(Craftsman cman:pages.getRecords()){
        		if(StringUtils.isNotBlank(cman.getManKey())){
        			cman.setProductNum(productionService.getProductionNumByManKey(cman.getManKey()));
        		}else{
        			cman.setProductNum(0);
        		}
        	}
        }
        pageInfo.setRows(pages.getRecords());
        pageInfo.setTotal(pages.getTotal());
         
        List<TTag> tagList=tTagService.selectList(null);
        List<TTag> tagNumList=craftsmanService.getTagNumMap();
        Map<String,Integer> tagNumMap=new HashMap<String,Integer>();
        if(tagNumList!=null && tagNumList.size()>0){
        	int count=0;
        	for(TTag temtag:tagNumList){
        		tagNumMap.put(temtag.getName(),temtag.getTagNum());
        		count+=temtag.getTagNum();
        	}
        	tagNumMap.put("alltag", count);
        }
        model.addAttribute("tagNumMap", tagNumMap);
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("rows",rows);
        model.addAttribute("tagList",tagList);
        model.addAttribute("prolist",  pages.getRecords());
    	model.addAttribute("craftsman", craftsman);
        return "admin/miind/index";
    }
    
    @RequestMapping(value="/brand",produces="text/html; charset=UTF-8")
    public String brand(Model model,Production production,String descr, Integer page, Integer rows, String sort,String order) {
    	if(page==null)
    		page=1;
    	if(rows==null){
    		rows=100;
    	}
    	
        PageInfo pageInfo = new PageInfo(page, rows, sort, order);
        if(StringUtils.isNotBlank(descr)){
	        production.setManName(descr.trim());
	        logger.info("查询条件descr="+descr+"  设置后的production="+production.getManName());
	    }
        
        Page<Production> pages = getPage(pageInfo);
        pages = productionService.selectPageProduction(pages, production);
        pageInfo.setRows(pages.getRecords());
        pageInfo.setTotal(pages.getTotal());
        Craftsman craftsman=null;
        if(StringUtils.isNotBlank(production.getManKey())){
        	EntityWrapper<Craftsman> ew = new EntityWrapper<Craftsman>();
     	    ew.eq("man_key", production.getManKey());
        	craftsman=craftsmanService.selectOne(ew);
        }
        if(production.getTagId()!=null && production.getTagId()>0){
	        EntityWrapper<Producttag> tagew = new EntityWrapper<Producttag>();
	        tagew.eq("tagid", production.getTagId());
	        int tagnum=this.producttagService.selectCount(tagew);
	        TTag tag=this.tTagService.selectById(production.getTagId());
	        if(tag!=null)
	        	model.addAttribute("tagname", tag.getName());
	        model.addAttribute("tagnum", tagnum);
        }
	    model.addAttribute("pageInfo", pageInfo);
	    model.addAttribute("prolist",  pages.getRecords());
		model.addAttribute("craftsman", craftsman);
		model.addAttribute("production", production);
	    return "admin/miind/brand";
    }
    
    
    @PostMapping("/getProductInfo")
    public void getProductInfo(HttpServletResponse response,String productKey,Long id) {
    	JSONObject json=new JSONObject();
    	Production product=productionService.selectById(id);
        PageInfo pageInfo = new PageInfo(1, 100, null, null);
        
        EntityWrapper<Productionimg> ew = new EntityWrapper<Productionimg>();
	    ew.eq("man_product_key", product.getManProductKey());
        Page<Productionimg> pages = getPage(pageInfo);
        pages = productionimgService.selectPage(pages, ew);
        pageInfo.setRows(pages.getRecords());
        pageInfo.setTotal(pages.getTotal());
        
        json.put("product", product);
        json.put("productList", pages.getRecords());
        ResponseUtil.write(response, json);
    }
    
    
    /**
     * 编辑
     * @param model
     * @param id
     * @return
     */
    @GetMapping("/signup")
    public String signup(Model model,HttpServletRequest request) {
    	String ip=this.getIpAddr(request);
    	logger.info("====statistics--To signup--IP="+ip);
        return "admin/miind/signup";
    }
    /**-
     * 编辑
     * @param 
     * @return
     */
	@PostMapping("/save")
    @ResponseBody
    public Object save(@Valid Craftsman craftsman,HttpServletRequest request) {
		String ip=this.getIpAddr(request);
		logger.info("====statistics--To Signup Save--IP="+ip+"  Craftsman Info:"+JSONObject.fromObject(craftsman).toString());
		try {
			/*
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			String pathRoot = request.getSession().getServletContext().getRealPath("");  
			// 品牌logo
			MultipartFile file3 = multipartRequest.getFile("pic_manBrandLogo");
			String path3="";
			if(file3 != null && file3.getSize()>0) {
				String uuid = UUID.randomUUID().toString().replaceAll("-","");  
				//获得文件类型（可以判断如果不是图片，禁止上传）  
	            String contentType=file3.getContentType();  
	            //获得文件后缀名称  
	            String imageName=contentType.substring(contentType.indexOf("/")+1);  
	            path3="/upload/images/"+uuid+"."+imageName;  
	            file3.transferTo(new File(pathRoot+path3));  				  
				craftsman.setManBrandLogo(path3);
			}
			*/
			boolean b = craftsmanService.insert(craftsman);
			craftsman.setManKey(craftsman.getId()+"");
			craftsmanService.updateById(craftsman);
			
			
			String[] productnames=request.getParameterValues("productnames");
			String[] productprices=request.getParameterValues("productprices");
			String[] productlinks=request.getParameterValues("productlinks");
			if(ArrayUtils.isEmpty(productnames)){
				craftsmanService.deleteById(craftsman.getId());
				 return renderError("添加失败,请填写产品信息！");
			}
			for(int i=0;i<productprices.length;i++){
				try{
					Float.valueOf(productprices[i]);
				}catch(Exception e){
					 craftsmanService.deleteById(craftsman.getId());
					 return renderError("添加失败,价格请填写数字！");
				}
			}
			
			for(int i=0;i<productnames.length;i++){
				Production production=new Production();
				production.setManName(productnames[i]);
				Float price=Float.valueOf(productprices[i]);
				production.setManPrice(price);
				production.setManProductlink(productlinks[i]);
				production.setManKey(craftsman.getManKey());
				production.setManNum(0);
			    b = productionService.insert(production);
			    production.setManProductKey(production.getId()+"");
				String[] imgids=request.getParameterValues("imgIds"+(i+1));
				for(int j=0;j<imgids.length;j++){
					if(StringUtils.isBlank(imgids[j])){
						continue;
					}
					Long imgid=Long.parseLong(imgids[j].trim());
					Productionimg pimgVO=productionimgService.selectById(imgid);
					pimgVO.setManProductKey(production.getManProductKey());
					pimgVO.setProdoctId(production.getId());
					if(StringUtils.isBlank(production.getManCover())){
			            production.setManCover(pimgVO.getManImg());
			        }
					productionimgService.updateById(pimgVO);
				}
				/*
			    //保存产品图片
			    String dir="/upload/images/"+production.getManKey()+"/"+production.getManProductKey()+"/";
			    List<MultipartFile> files=multipartRequest.getFiles("productimgs"+(i+1));
				if(files!=null && files.size()>0){
					for(int j=0;j<files.size();j++){
						MultipartFile tempfile =files.get(j);
						if(tempfile != null && tempfile.getSize()>0) {
							if(tempfile!=null && tempfile.getSize()>0){
								String path=this.saveImg(pathRoot,dir, tempfile);
								Productionimg pimgVO=new Productionimg();
					            pimgVO.setManProductKey(production.getManProductKey());
					            pimgVO.setManImg(path);
					            if(StringUtils.isBlank(production.getManCover())){
					            	production.setManCover(path);
					            }
					            pimgVO.setProdoctId(production.getId());
					            productionimgService.insert(pimgVO);
							}
						}
					}
				}
				*/
				//更新产品新
				productionService.updateById(production);
				
				//保存页签信息
				Producttag tagVO=new Producttag();
				tagVO.setProductKey(production.getId()+"");
				tagVO.setPruductid(production.getId());
				tagVO.setTagid(2L);//2017报名
				tagVO.setCreateTime(new Date());
				producttagService.insert(tagVO);
				
			}
			
	        if (b) {
	        	logger.info("====statistics--To Signup Save--IP="+ip+"  保存成功");
	            return renderSuccess("添加成功！");
	        } else {
	        	logger.info("====statistics--To Signup Save--IP="+ip+"  保存失败");
	            return renderError("添加失败,请检查信息是否填写正确！");
	        }
	        
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			logger.error("====statistics--To Signup Save Exception --IP="+ip,e);
			return renderError("添加失败,请检查信息是否填写正确！"+e.getMessage());
		}
		//logger.info("====statistics--To Signup Save--IP="+ip+"  保存失败");
		//return renderError("添加失败,请检查信息是否填写正确！");
   }
	
	 /**
     * 上传
     * @param id
     * @return
     */
    @PostMapping("/upload")
    @ResponseBody
    public Object upload(@RequestParam("file") MultipartFile file,HttpServletRequest request) {
    	JSONObject json=new JSONObject();
    	json.put("success",false);
    	json.put("msg","");
        //用来检测程序运行时间
    	logger.info("开始上传文件："+file.getName()+"  size:"+file.getSize());
    	SimpleDateFormat sf=new SimpleDateFormat("yyyyMMdd");
    	String datestr=sf.format(new Date());
        try {
        	//校验文件合法性
        	List<String> allowType = Arrays.asList("image/bmp","image/png","image/gif","image/jpg","image/jpeg","image/pjpeg");  
            if(!allowType.contains(file.getContentType())){
            	json.put("msg","请上传jpeg、jpg、png、bmp格式的图片");
            	return json;
            }
            if(file.getSize()>1024*1024*5){
            	json.put("msg","您上传的图片过大，请上传5M以内的图片");
            	return json;
            }
            
        	String pathRoot = request.getSession().getServletContext().getRealPath("");  
        	String path="/upload/images/"+datestr+"/";
            String imgpath=saveImg(pathRoot,path,file);
			Productionimg pimgVO=new Productionimg();
            pimgVO.setManImg(imgpath);
            productionimgService.insert(pimgVO);
            json.put("imgid",pimgVO.getId());
            json.put("imgpath",pimgVO.getManImg());
            json.put("success",true);
           logger.info("文件开始上传完毕："+file.getName()+"  size:"+file.getSize());
        } catch (Exception e) {
        	this.logger.error("文件上传异常："+e.getMessage(),e);
            e.printStackTrace();
        }
        return json;
    }
    
    
    /**
     * 是否入围
     * @param id
     * @return
     */
    @PostMapping("/changeselect")
    @ResponseBody
    public Object changeselect(HttpServletRequest request,Long id,Integer selectvalue) {
    	JSONObject json=new JSONObject();
    	json.put("success",false);
    	json.put("msg","更新失败！");
    	
    	if(id!=null && id>0 && selectvalue!=null && selectvalue>=0){
    		Craftsman craftsman=this.craftsmanService.selectById(id);
    		if(craftsman!=null){
    			craftsman.setSelected(selectvalue);
    			craftsmanService.updateById(craftsman);
    			json.put("success",true);
    	    	json.put("msg","更新成功！");
    	    	return json;
    		}
    	}
    	
        return json;
    }
	 public String saveImg(String pathRoot,String dir,MultipartFile file){
	    	String imgPath=null;
	    	if(file != null && file.getSize()>0) {
	    		String uuid = UUID.randomUUID().toString().replaceAll("-","");  
				//获得文件类型（可以判断如果不是图片，禁止上传）  
	            String contentType=file.getContentType();
	            //获得文件后缀名称  
	            String imageName=contentType.substring(contentType.indexOf("/")+1);  
	            String path=dir+uuid+"."+imageName;  
	            File tFile=new File(pathRoot+path);
	            if(!tFile.getParentFile().exists()){
	            	tFile.mkdirs();
	            }
				try {
					file.transferTo(tFile);
					return path;
				} catch (Exception e) {
					e.printStackTrace();
					logger.error("图片上传异常：",e);
				}
	    	}
	    	return imgPath;
	 }
}
